#!/usr/bin/env dash
# take input from bspc subscribe, emit desktop stuff information.
# todo: consider reimplementing click handling.

focusMonitor=$(bspc query -M -m $mon --names)

# options/variables to account for:
#desktopDisplay=icon         # [icon|name] - display desktop names or DO/DF variables.
#showFreeDesktops=true       # option to show nothing for free desktops (but still show the focused desktop)
#NoModeToggle=true           # true or false

# temp/compat
DO="$p_desktop_occupied_label"
DF="$p_desktop_empty_label"
DT="$p_desktop_tiling_label"
DM="$p_desktop_monocle_label"

NoModeToggle="$p_desktop_mode_toggle"
showFreeDesktops="$p_desktop_show_free"
desktopDisplay="$p_desktop_display_name"

while read -r line; do
    [ "$cache" = "$line" ] && continue
    cache="$line"

    if $p_desktop_only_active; then
        icon desktop
        bspc query -D -m $mon -d focused --names
        continue
    fi

    input="$(echo $line | grep -Eo "[Mm]${focusMonitor}[^mM]*")"
    meta start

    IFS=':'
    # set delimited var as top level arguments
    set -- ${input#?}
    IFS=

    # the desktop name
    shift

    desktop_index=1
    while [ $# -gt 0 ] ; do
        meta mouse_left "bspc desktop -f ${mon}:^${desktop_index}"
        desktop_index=$((desktop_index + 1))

        item=$1
        ident="$(echo $item | cut -c1)"
        content="$(echo $item | cut -c2-)"
        layout=false
        free=false
        active=false

        case $ident in
            O) dDisplay="$DO"; active=true; meta active;; #active occupied desktop
            o) dDisplay="$DO"; meta reset;;  #inactive occupied desktop
            F) dDisplay="$DF"; free=true; active=true; meta active;; #active free desktop
            f) dDisplay="$DF"; free=true; meta reset;;  #inactive free desktop
            U) dDisplay="$DO"; active=true;; # meta invert;; #active urgent desktop
            u) dDisplay="$DO";; # meta invert;; #inactive urgent desktop

            L) layout=true
               meta reset
               [ "$content" = "T" ] && dDisplay="$DT" || dDisplay="$DM"
               $NoModeToggle && dDisplay=""
               [ ! -z "$dDisplay" ] && meta mouse_left bspc desktop -l next
               ;;
            *) layout=true; dDisplay="" ;;
        esac

        if ! $layout; then
            [ "$desktopDisplay" = "name" ] && dDisplay="$content"
            if ! $showFreeDesktops && ! $active; then
                ! $free && echo "$dDisplay"
            else
                echo "$dDisplay"
            fi
        else
            echo "$dDisplay"
        fi

        shift
    done

    meta end
done
